package com.lq.dubbo.rocketmq.shop.mq;

import com.alibaba.fastjson.JSON;
import com.lq.dubbo.rocketmq.shop.constant.ShopCode;
import com.lq.dubbo.rocketmq.shop.entity.MQEntity;
import com.lq.dubbo.rocketmq.shop.mapper.TradeCouponMapper;
import com.lq.dubbo.rocketmq.shop.shop_pojo.TradeCoupon;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @program: dubborocketmqshop
 * @description: 消息监听
 * 因为订单回退,用户,商品,订单,优惠券系统登都需要监听做相应设置,所以messageModel(消费模式)设置为广播消费模式
 * @author: LQ
 * @create: 2021-06-24 16:25
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.order.topic}", consumerGroup = "${mq.order.consumer.group.name}", messageModel = MessageModel.BROADCASTING)
public class CancelMqListener implements RocketMQListener<MessageExt> {

    @Autowired
    private TradeCouponMapper couponMapper;

    // MessageExt 继承Message 有消息ID
    @Override
    public void onMessage(MessageExt messageExt) {
        String body = null;
        MQEntity mqEntity = null;
        try {
            // 1.解析消息
            body = new String(messageExt.getBody(), "UTF-8");
            mqEntity = JSON.parseObject(body, MQEntity.class);
            log.info("接收消息处理成功");
            // 2.查询当前优惠券信息
            Long couponId = mqEntity.getCouponId();
            if (mqEntity.getCouponId() != null) {
                TradeCoupon coupon = couponMapper.selectByPrimaryKey(couponId);
                // 3. 更改优惠券状态
                coupon.setOrderId(null);
                coupon.setUsedTime(null);
                coupon.setIsUsed(ShopCode.SHOP_COUPON_UNUSED.getCode());
                couponMapper.updateByPrimaryKey(coupon);
            }
            log.info("订单:" + mqEntity.getOrderId() + "回退优惠券成功!");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("订单:" + mqEntity.getOrderId() + "回退优惠券失败!");
        }
    }
}
